<template>
    <div class="journal-management">
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入期刊名称查询" clearable @clear="handleClearSearch"
                class="search-input" />
            <el-button type="primary" @click="openDialog('add')">入库登记</el-button>
        </div>

        <el-table :data="journals" stripe border>
            <el-table-column prop="journal_name" label="期刊名称" />
            <el-table-column prop="year" label="年份" />
            <el-table-column prop="volume" label="卷号" />
            <el-table-column prop="issue" label="期号" />
            <el-table-column prop="location_name" label="馆藏地" />
            <el-table-column prop="stock" label="库存" />
            <el-table-column prop="created_at" label="创建时间" />
            <el-table-column prop="updated_at" label="更新时间" />

            <!-- 新增图片列 -->
            <el-table-column label="期刊图片">
                <template #default="{ row }">
                    <el-image v-if="row.image_url" :src="row.image_url" style="width: 100px; height: 100px;" />
                </template>
            </el-table-column>

            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" @click="openDialog('edit', row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="handlePageChange" class="pagination" />

        <el-dialog v-model="dialogVisible" width="30%" :title="dialogTitle">
            <el-form :model="currentJournal" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="期刊名称" prop="directory_id">
                    <el-select v-model="currentJournal.directory_id" placeholder="请选择期刊名称">
                        <el-option v-for="directory in journalDirectories" :key="directory.directory_id"
                            :label="directory.journal_name" :value="directory.directory_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="馆藏地" prop="location_id">
                    <el-select v-model="currentJournal.location_id" placeholder="请选择馆藏地">
                        <el-option v-for="location in libraryLocations" :key="location.location_id"
                            :label="location.location_name" :value="location.location_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input type="number" v-model="currentJournal.stock" placeholder="请输入库存" />
                </el-form-item>
                <el-form-item label="年份" prop="year">
                    <el-input type="number" v-model="currentJournal.year" placeholder="请输入年份" />
                </el-form-item>
                <el-form-item label="卷号" prop="volume">
                    <el-input type="number" v-model="currentJournal.volume" placeholder="请输入卷号" />
                </el-form-item>
                <el-form-item label="期号" prop="issue">
                    <el-input type="number" v-model="currentJournal.issue" placeholder="请输入期号" />
                </el-form-item>
                <el-form-item label="期刊图片" prop="image_url">
                    <el-upload action="/api/upload/image" list-type="picture-card" :file-list="fileList"
                        :on-success="handleImageUploadSuccess" :on-error="handleImageUploadError"
                        :on-remove="handleImageRemove" name="file">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-image v-if="currentJournal.image_url" :src="currentJournal.image_url"
                        style="width: 100px; height: 100px; margin-top: 10px;" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { journalApi, libraryLocationApi, journalDirectoryApi } from '@/request/apiService';
import { ElMessageBox } from 'element-plus';

// 数据定义
const journals = ref([]);
const currentJournal = ref({ journal_id: '', directory_id: '', year: '', volume: '', issue: '', location_id: '', stock: '', image_url: '' });
const dialogVisible = ref(false);
const dialogTitle = ref('');
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const libraryLocations = ref([]);
const journalDirectories = ref([]);
const form = ref(null);
const fileList = ref([]);

const rules = {
    directory_id: [{ required: true, message: '请选择期刊名称', trigger: 'change' }],
    year: [{ required: true, message: '请输入年份', trigger: 'blur' }, {
        validator:(rule, value, callback) => {
            if (!value) {
                callback(); return;
            }
            const yearRegex = /^(20([0-4][0-9]|50))$/;
            if (!yearRegex.test(value)) {
                callback(new Error('年份信息不正确'));
            } else {
                callback();
            }
        }
    }],
    volume: [{ required: true, message: '请输入卷号', trigger: 'blur' }],
    issue: [{ required: true, message: '请输入期号', trigger: 'blur' }],
    location_id: [{ required: true, message: '请选择馆藏地', trigger: 'change' }],
    stock: [{ required: true, message: '请输入库存', trigger: 'blur' }, {
        validator: (rule, value, callback) => {
            if (!value) {
                callback(); return;
            }
            const stockRegex = /^\d+$/;
            if (!stockRegex.test(value)) {
                callback(new Error('库存数量必须大于等于零'));
            } else {
                callback();
            }
        }
    }],
};

// 获取期刊列表
const fetchJournals = async () => {
    try {
        const { data, total: totalCount } = await journalApi.getJournalList({
            page: currentPage.value,
            pageSize: pageSize.value,
            search: search.value,
        });
        journals.value = data;
        total.value = totalCount;
    } catch (error) {
        console.error('获取期刊列表失败', error);
    }
};

// 获取馆藏地列表
const fetchLibraryLocations = async () => {
    try {
        const { data } = await libraryLocationApi.getLibraryLocationList({ page: 1, pageSize: 100 });
        libraryLocations.value = data;
    } catch (error) {
        console.error('获取馆藏地列表失败', error);
    }
};

// 获取期刊目录列表
const fetchJournalDirectories = async () => {
    try {
        const { data } = await journalDirectoryApi.getDirectoryList({ page: 1, pageSize: 100 });
        journalDirectories.value = data;
    } catch (error) {
        console.error('获取期刊目录失败', error);
    }
};

// 打开对话框
const openDialog = (type, journal = { journal_id: '', directory_id: '', year: '', volume: '', issue: '', location_id: '', stock: '', image_url: '' }) => {
    if (type === 'add') {
        dialogTitle.value = '入库登记';
        currentJournal.value = { journal_id: '', directory_id: '', year: '', volume: '', issue: '', location_id: '', stock: '', image_url: '' };
    } else if (type === 'edit') {
        dialogTitle.value = '编辑期刊';
        currentJournal.value = { ...journal };
    }
    dialogVisible.value = true;
};

// 处理图片上传成功
const handleImageUploadSuccess = (response, file, fileList) => {
    currentJournal.value.image_url = response.url; // 假设返回的图片 URL 存储在 response.url
};

// 处理图片上传失败
const handleImageUploadError = (err, file, fileList) => {
    console.error('图片上传失败:', err);
};

// 处理删除图片
const handleImageRemove = (file, fileList) => {
    currentJournal.value.image_url = ''; // 删除时清空图片路径
};

// 保存期刊
const handleSave = async () => {
    if (!form.value) return;
    form.value.validate(async (valid) => {
        if (!valid) return;

        const { journal_id, directory_id, year, volume, issue, location_id, stock, image_url } = currentJournal.value;
        try {
            if (journal_id) {
                await journalApi.updateJournal({ journal_id, directory_id, year, volume, issue, location_id, stock, image_url });
            } else {
                await journalApi.addJournal({ directory_id, year, volume, issue, location_id, stock, image_url });
            }
            await fetchJournals();
            dialogVisible.value = false;
        } catch (error) {
            console.error('保存期刊失败', error);
        }
    });
};

// 删除期刊
const handleDelete = (journal) => {
    ElMessageBox.confirm('此操作将永久删除该期刊, 是否继续?', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                await journalApi.deleteJournal({ journal_id: journal.journal_id });
                await fetchJournals();
            } catch (error) {
                console.error('删除期刊失败', error);
            }
        })
        .catch(() => console.log('删除操作已取消'));
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    currentPage.value = 1;
    fetchJournals();
};

// 分页变化
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchJournals();
};

// 页面加载时获取数据
onMounted(() => {
    fetchJournals();
    fetchLibraryLocations();
    fetchJournalDirectories();
});
</script>

<style scoped>
.journal-management {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 20px;
}

.pagination {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}

.el-image {
    margin-top: 10px;
    width: 100px;
    height: 100px;
}
</style>
